import java.io.*;
import java.util.regex.*;

final class MusicLibrary extends HasNameList<Artist> {

  private final File lib;
  private boolean filled;

  MusicLibrary(File lib) {
    super(lib.getAbsolutePath());
    this.lib = lib;
  }

  Artist newInstance(String name) {
    return new Artist(name,this);
  }

  public void fill() {
    if (filled) return;
    try {
      fillInternal();
      System.out.println(this);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      filled = true;
    }
  }

  private void fillInternal() throws IOException {
    BufferedReader in = new BufferedReader(new FileReader(lib));
    String line;
    String nameStr   = null;
    String artistStr = null;
    String albumStr  = null;
    while ((line = in.readLine()) != null) {
      Pattern p;
      Matcher m;

      p = Pattern.compile(".*<key>Name</key><string>([^<]+)</string>.*");
      m = p.matcher(line);
      if (m.matches()) {
        nameStr = m.group(1);
      }

      p = Pattern.compile(".*<key>Artist</key><string>([^<]+)</string>.*");
      m = p.matcher(line);
      if (m.matches()) {
        artistStr = m.group(1);
      }

      p = Pattern.compile(".*<key>Album</key><string>([^<]+)</string>.*");
      m = p.matcher(line);
      if (m.matches()) {
        albumStr = m.group(1);
      }

      if (nameStr != null && artistStr != null && albumStr != null) {

        Artist artist = getOrCreate(artistStr);
        Album  album  = artist.getOrCreate(albumStr);
        Track  track  = album.getOrCreate(nameStr);

        nameStr   = null;
        artistStr = null;
        albumStr  = null;
      }

    }
    in.close();
  }
  
}